# !pip install -U memory_profiler

import math,time,psutil,resource,os
from random import randint

def length(worker:list,task:list)->float:#求两个点的长度
    distance = (worker[2]-task[2])**2+(worker[3]-task[2])**2
#     print(distance)
    distance = pow(distance,1/2)
    return distance
#     print(distance)

def length2(worker:list,task:list)->float:#求两个点的长度,不开方的
    distance = (worker[2]-task[2])**2+(worker[3]-task[3])**2
    return distance

def satisfyLoc(worker:list,task:list)->bool:#验证任务与工作者之间是否符合活动范围内
    if length2(worker,task) > worker[4]*worker[4]:
        return False
    return True

def satifyTime(worker:list,task:list)->bool:
    if (worker[0] < task[4] and task[0] < worker[6]) is False:
        return False
    return True

def satify(worker:list,task:list)->bool:
    if satifyTime(worker,task) and satisfyLoc(worker,task):
        return True
    return False
    

def calcCost(worker:list,task:list)->float:
    if satisfyLoc(worker,task) and satifyTime(worker,task):
        return worker[7]*task[5]
    else:
        return 0.0

def dcmp(a:float,b:float)->bool:
    return math.isclose(a,b,rel_tol=1e-6)
def dcmp(a:float)->bool:
    return abs(a)<1e-6


workers = []
tasks = []
queue = []
def readData(fileName):
    with open(fileName,'r') as f:
        data = f.readlines()
        first = data[0].strip("\n").split(" ")
        workerNum = int(first[0])
        taskNum = int(first[1])
        utilityMax = int(first[2])
        theta = round(math.log(utilityMax+1.0),0)
        theta = int(theta)
        for i in range(1,len(data)):
            node = data[i].strip("\n").split(" ")
            if node[1]=='w':
                node[0]=int(node[0])#到达时间
                node[2]=float(node[2])#纬度
                node[3]=float(node[3])#经度
                node[4]=float(node[4])#半径
                node[5]=int(node[5])#能力
                node[6]=int(node[6])+node[0]#停留的时间
                node[7]=float(node[7])#接受率
                if len(node) < 9:#最后一个用来记录等待多久匹配
                    node.append(theta-1)
                else:
                    node[8] = theta - 1
                workers.append(node)
            else:
                node[0]=int(node[0])#到达时间
                node[2]=float(node[2])#纬度
                node[3]=float(node[3])#经度
                node[4]=int(node[4])+node[0]#停留的时间
                node[5]=float(node[5])#支付的报酬
                if len(node) < 7:
                    node.append(theta-1)
                else:
                    node[6] = theta -1
                tasks.append(node)
            queue.append(node)
    return utilityMax

def selectTask(worker,taskList,threshold,curTime):
    maxCost = 0.0
    tindex = -1
    for i,task in enumerate(taskList):
        tempCost = calcCost(worker,task)
        if tempCost >= threshold and tempCost > maxCost and worker[6] >= curTime and task[4] >= curTime:
            maxCost = tempCost
            tindex = i
    if tindex != -1:#匹配成功，删除成功匹配的任务
        taskList.pop(tindex)
    return maxCost
                
                

def selectWorker(task,workerList,threshold,curTime):
    maxCost = 0.0
    windex = -1
    for i,worker in enumerate(workerList):
        tempCost = calcCost(worker,task)
        if tempCost >= threshold and tempCost > maxCost and worker[6] >= curTime and task[4] >= curTime:
            maxCost = tempCost
            windex = i
    if windex != -1:#匹配成功，删除成功匹配的工作者
        workerList.pop(windex)
    return maxCost
        
def match(workerList,taskList,curTime):
    ans = 0
    successNum = 0
    nMatchW = []
    nMatchT = []
    for windex,worker in enumerate(workerList):
        k = worker[8]
        threshold = math.exp(k)
        maxCost = 0.0
        tmid = -1
        for tindex,task in enumerate(taskList):
            tempCost = calcCost(worker,task)
            if tempCost >= threshold and tempCost > maxCost and worker[6] >= curTime and task[4] >= curTime:
                maxCost = tempCost
                tmid = tindex
        if tmid != -1:#匹配成功
            taskList.pop(tmid)
            ans += maxCost
            successNum += 1
        else:
            if worker[8] > 0:
                worker[8] -= 1
            if worker[6] >= curTime:
                nMatchW.append(worker)
#             nMatchW.append(worker)
    for task in taskList:
        if task[4] >= curTime:
            nMatchT.append(task)
    return nMatchW,nMatchT,ans,successNum
    
    
def waterFilter():
    mworkers = []
    mtasks = []
    curTime = 0
    utility = 0.0
    matchNum = 0
    lastTime = -1
    for item in queue:
        crowType = item[1]
        curTime = item[0]
        if crowType == "w":
            # print(item[7])
            cap = item[5]
            for w in range(cap):
                mworkers.append(item)
        else:
            mtasks.append(item)
        if lastTime != curTime:
            mworkers,mtasks,tempU,tempN = match(mworkers,mtasks,curTime)
            utility += tempU
            matchNum += tempN
            lastTime = curTime
    return utility,matchNum

def solve():
    memory = resource.getrusage(resource.RUSAGE_SELF)
    avgUtility = 0.0 
    avgTime = 0
    avgMemory = 0
    avgMatchNu = 0
    startTime = time.perf_counter()
    avgUtility,avgMatchNu=waterFilter()
    endTime = time.perf_counter()
    avgTime += endTime - startTime
    avgMemory += memory.ru_maxrss
    # print(avgUtility,avgTime,avgMemory,avgMatchNu)
    return [avgUtility,avgTime,avgMemory,avgMatchNu]


def varyWorkers(testNUm):#测试变化的工作者，其余变量保持不变
    fin = open("./result/synthetic/data/varyworkers.txt",'a+',encoding='utf-8')
    # for w in  [100, 200, 500, 1000, 5000]:
    for w in  [100]:
        fileName = f"./dataset/synthetic/{w}_2500_1_2.0_0.5_6_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            # workers.clear()
            # tasks.clear()
            # queue.clear()
            # utilityMax = readData(fileName)
            for n in range(testNUm):#测试次数
                workers.clear()
                tasks.clear()
                queue.clear()
                readData(fileName)#放到for循环就是为初始化队列queue，因为列表随着被赋值的元素修改而被修改
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "WF(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")
        
    #文件关闭
    fin.close()


def varyTasks(testNUm):#测试变化的工作者
    fin = open("./result/synthetic/data/varytasks.txt",'a+',encoding='utf-8')
    for t in   [500, 1000, 2500, 5000, 10000]:
        fileName = f"./dataset/synthetic/500_{t}_1_2.0_0.5_6_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            # workers.clear()
            # tasks.clear()
            # queue.clear()
            # utilityMax = readData(fileName)
            for n in range(testNUm):#测试次数
                workers.clear()
                tasks.clear()
                queue.clear()
                readData(fileName)
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "WF(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")
        
    #文件关闭
    fin.close()

def varyCw(testNUm):#测试工作者能力变化的影响
    fin = open("./result/synthetic/data/varycw.txt",'a+',encoding='utf-8')
    for cw in [1, 2, 3, 4, 5]:
        fileName = f"./dataset/synthetic/500_2500_{cw}_2.0_0.5_6_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            # workers.clear()
            # tasks.clear()
            # queue.clear()
            # utilityMax = readData(fileName)
            for n in range(testNUm):#测试次数
                workers.clear()
                tasks.clear()
                queue.clear()
                readData(fileName)
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "WF(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")
        
    #文件关闭
    fin.close()

def varyRw(testNUm):#测试工作者半径变化的影响
    fin = open("./result/synthetic/data/varyrw.txt",'a+',encoding='utf-8')
    for rw in [1.0, 1.5, 2.0, 2.5, 3.0]:
        fileName = f"./dataset/synthetic/500_2500_1_{rw}_0.5_6_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            # workers.clear()
            # tasks.clear()
            # queue.clear()
            # utilityMax = readData(fileName)
            for n in range(testNUm):#测试次数
                workers.clear()
                tasks.clear()
                queue.clear()
                readData(fileName)
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "WF(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")
        
    #文件关闭
    fin.close()

def varyDw(testNUm):#工作者接受率变化的影响
    fin = open("./result/synthetic/data/varydw.txt",'a+',encoding='utf-8')
    for dw in [0.1, 0.3, 0.5, 0.7, 0.9]:
        fileName = f"./dataset/synthetic/500_2500_1_2.0_{dw}_6_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            # workers.clear()
            # tasks.clear()
            # queue.clear()
            # utilityMax = readData(fileName)
            for n in range(testNUm):#测试次数
                workers.clear()
                tasks.clear()
                queue.clear()
                readData(fileName)
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "WF(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def varyDdl(testNUm):#截至时间变化的影响
    fin = open("./result/synthetic/data/varyddl.txt",'a+',encoding='utf-8')
    for ddl in [2, 4, 6, 8, 10]:
        fileName = f"./dataset/synthetic/500_2500_1_2.0_0.5_{ddl}_10/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            # workers.clear()
            # tasks.clear()
            # queue.clear()
            # utilityMax = readData(fileName)
            for n in range(testNUm):#测试次数
                workers.clear()
                tasks.clear()
                queue.clear()
                readData(fileName)
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "WF(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def varyPtsNormal(testNUm):#正态分布任务支付大小变化的影响
    fin = open("./result/synthetic/data/varyptsnormal.txt",'a+',encoding='utf-8')
    for pt in [2, 5, 10, 15, 20]:
        fileName = f"./dataset/synthetic/500_2500_1_2.0_0.5_6_{pt}/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            # workers.clear()
            # tasks.clear()
            # queue.clear()
            # utilityMax = readData(fileName)
            for n in range(testNUm):#测试次数
                workers.clear()
                tasks.clear()
                queue.clear()
                readData(fileName)
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "WF(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def varyPtsExponentail(testNUm):#指数分布任务支付大小变化的影响
    fin = open("./result/synthetic/data/varyptsexponentail.txt",'a+',encoding='utf-8')
    for pt in [2, 5, 10, 15, 20]:
        fileName = f"./dataset/synthetic/500_2500_1_2.0_0.5_6_{pt+100}/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            # workers.clear()
            # tasks.clear()
            # queue.clear()
            # utilityMax = readData(fileName)
            for n in range(testNUm):#测试次数
                workers.clear()
                tasks.clear()
                queue.clear()
                readData(fileName)
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "WF(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def varyPtsUniform(testNUm):#任务支付大小变化的影响
    fin = open("./result/synthetic/data/varyptsuniform.txt",'a+',encoding='utf-8')
    for pt in [2, 5, 10, 15, 20]:
        fileName = f"./dataset/synthetic/500_2500_1_2.0_0.5_6_{pt+1000}/data_00.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            # workers.clear()
            # tasks.clear()
            # queue.clear()
            # utilityMax = readData(fileName)
            for n in range(testNUm):#测试次数
                workers.clear()
                tasks.clear()
                queue.clear()
                readData(fileName)
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "WF(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def scalability(testNUm):
    fin = open("./result/synthetic/data/scalability.txt",'a+',encoding='utf-8')
    for s in range(1,11):
        w = s*10**3
        t = s*10**4
        fileName = f"./dataset/synthetic/{w}_{t}_1_2.0_0.5_6_10/data_00.txt"
        # print(fileName)
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            # workers.clear()
            # tasks.clear()
            # queue.clear()
            # utilityMax = readData(fileName)
            for n in range(testNUm):#测试次数
                workers.clear()
                tasks.clear()
                queue.clear()
                readData(fileName)
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "WF(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def EverySenderCw(testNUm):#真实数据集
    fin = open("./result/real/data/varyEverysenderCw.txt",'a+',encoding='utf-8')
    for cap in [1,2,3,4,5,6,7,8,9,10]:
        fileName = f"./dataset/real/EverySender_cap{cap}/data_00_time.txt"
        ansList = [0,0,0,0]
        if os.path.exists(fileName):
            # workers.clear()
            # tasks.clear()
            # queue.clear()
            # readData(fileName)
            for n in range(testNUm):#测试次数
                workers.clear()
                tasks.clear()
                queue.clear()
                readData(fileName)
                ans=solve()
                for ansi in range(4):
                    ansList[ansi] += ans[ansi]
            writeStr = "WF(ours)"
            for result in ansList:
                temp = result/testNUm
                print(temp,end=' ')
                writeStr +=" "+str(temp)
            print()
            writeStr += "\n"
            fin.write(writeStr)
        else:
            print(fileName,"文件不存在")

def  gMissionCw(testNUm):
        fin = open("./result/real/data/varygMissionCw.txt",'a+',encoding='utf-8')
        for cap in [1,2,3,4,5,6,7,8,9,10]:
            fileName = f"./dataset/real/gMission_cap{cap}/data_00_time.txt"
            ansList = [0,0,0,0]
            if os.path.exists(fileName):
                # workers.clear()
                # tasks.clear()
                # queue.clear()
                # readData(fileName)
                for n in range(testNUm):#测试次数
                    workers.clear()
                    tasks.clear()
                    queue.clear()
                    readData(fileName)
                    ans=solve()
                    for ansi in range(4):
                        ansList[ansi] += ans[ansi]
                writeStr = "WF(ours)"
                for result in ansList:
                    temp = result/testNUm
                    print(temp,end=' ')
                    writeStr +=" "+str(temp)
                print()
                writeStr += "\n"
                fin.write(writeStr)
            else:
                print(fileName,"文件不存在")

if __name__ == "__main__":
    testNUm = 10
    varyWorkers(testNUm)
    varyTasks(testNUm)
    varyCw(testNUm)
    varyRw(testNUm)
    varyDw(testNUm)
    varyDdl(testNUm)

    varyPtsNormal(testNUm)
    varyPtsExponentail(testNUm)
    varyPtsUniform(testNUm)
    scalability(testNUm)
    EverySenderCw(testNUm)
    gMissionCw(testNUm)